package com.addplus.townmall.server.scheduled.scheduletask;

import com.addplus.townmall.server.api.constant.StringConstant;
import com.addplus.townmall.server.api.mapper.town.*;
import com.addplus.townmall.server.api.model.demo.DemoUser;
import com.addplus.townmall.server.api.model.town.*;
import com.addplus.townmall.server.api.utils.DataUtils;
import com.addplus.townmall.server.api.utils.date.DateUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 类名: SpikeActiceStatusTask
 *
 * @author zhangjiehang
 * @version V1.0
 * @date 2018/11/8 2:57 PM
 * @description 类描述: 秒杀活动状态更改定时器
 */
@Component
public class SpikeActiceStatusTask {

    private Logger logger = LoggerFactory.getLogger(SpikeActiceStatusTask.class);


    @Autowired
    CouponMapper couponMapper;

    @Autowired
    private SpikeActiveMapper spikeActiveMapper;

    @Autowired
    private ShopParticipateActiveMapper shopParticipateActiveMapper;

    @Autowired
    OrderItemsFightMapper orderItemsFightMapper;

    @Autowired
    TownOrderFightMapper townOrderFightMapper;
    @Autowired
    MemberIntegralMapper memberIntegralMapper;

    /**
     * 方法描述：处理未开始状态的任务转换成开始状态
     *
     * @throws Exception
     * @author zhangjiehang
     * @date 2018/11/8 3:00 PM
     */
    @Scheduled(cron = "0 */1 * * * ?")
    private void processUnStart() throws Exception {
        logger.info("秒杀场次开始活动定时任务开始");
        QueryWrapper<SpikeActive> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        queryWrapper.eq("online_status", 1);
        queryWrapper.eq("is_deleted", 0);
        queryWrapper.orderByAsc("begin_date");
        List<SpikeActive> spikeActives = spikeActiveMapper.selectList(queryWrapper);
        if (spikeActives == null || spikeActives.isEmpty()) {
            logger.info("秒杀活动，未开始状态的活动列表未空");
            return;
        } else {
            LocalDateTime localDateTimeNow = LocalDateTime.now();
            LocalDateTime localDateTimeNowFormat = LocalDateTime.of(localDateTimeNow.toLocalDate(), LocalTime.of(localDateTimeNow.getHour(), localDateTimeNow.getMinute(), 0));
            spikeActives.forEach(item -> {
                LocalDateTime localBeginDate = DateUtils.dateToLocalDateTimeSecondZero(item.getBeginDate());
                LocalDateTime localEndDate = DateUtils.dateToLocalDateTimeSecondZero(item.getEndDate());
                if (localDateTimeNowFormat.isEqual(localBeginDate) || localDateTimeNowFormat.isAfter(localBeginDate)) {
                    UpdateWrapper<SpikeActive> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("id", item.getId());
                    updateWrapper.eq("online_status", 1);
                    int status = item.getStatus();
                    if (localDateTimeNowFormat.isBefore(localEndDate)) {
                        status = 1;
                        updateWrapper.set("status", status);
                    } else {
                        status = 2;
                        updateWrapper.set("status", status);
                    }
                    updateWrapper.set("gmt_modified", localDateTimeNow);
                    spikeActiveMapper.update(new SpikeActive(), updateWrapper);
                    // 更改关联的商品互动表
                    updateShopParticipateActive(item.getId(), status);
                }
            });
        }
        logger.info("秒杀场次开始活动定时任务完成");
    }

    /**
     * 方法描述：处理进行中状态的任务转换成结束状态
     *
     * @throws Exception
     * @author zhangjiehang
     * @date 2018/11/8 3:00 PM
     */
    @Scheduled(cron = "0 */1 * * * ?")
    private void processSpikeFinish() throws Exception {
        logger.info("秒杀场次结束活动定时任务开始");
        QueryWrapper<SpikeActive> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.eq("online_status", 1);
        queryWrapper.eq("is_deleted", 0);
        queryWrapper.orderByAsc("begin_date");
        List<SpikeActive> spikeActives = spikeActiveMapper.selectList(queryWrapper);
        if (spikeActives == null || spikeActives.isEmpty()) {
            logger.info("秒杀活动，进行中状态的活动列表未空");
            return;
        } else {
            LocalDateTime localDateTimeNow = LocalDateTime.now();
            LocalDateTime localDateTimeNowFormat = LocalDateTime.of(localDateTimeNow.toLocalDate(), LocalTime.of(localDateTimeNow.getHour(), localDateTimeNow.getMinute(), 0));
            spikeActives.forEach(item -> {
                LocalDateTime localEndDate = DateUtils.dateToLocalDateTimeSecondZero(item.getEndDate());
                if (localDateTimeNowFormat.isEqual(localEndDate) || localDateTimeNowFormat.isAfter(localEndDate)) {
                    UpdateWrapper<SpikeActive> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("id", item.getId());
                    updateWrapper.eq("online_status", 1);
                    updateWrapper.set("status", 2);
                    updateWrapper.set("gmt_modified", localDateTimeNow);
                    spikeActiveMapper.update(new SpikeActive(), updateWrapper);
                    updateShopParticipateActive(item.getId(), 2);
                }
            });
        }
        logger.info("秒杀场次开始活动定时任务完成");
    }


    /**
     * 方法描述：更新商品关联活动表
     *
     * @throws Exception
     * @author zhangjiehang
     * @date 2018/11/8 4:45 PM
     */
    private void updateShopParticipateActive(Integer spikeActiveId, Integer staus) {
        UpdateWrapper<ShopParticipateActive> updateWrapper = new UpdateWrapper<ShopParticipateActive>();
        updateWrapper.eq("shop_active_type", 1);
        updateWrapper.eq("shop_obj_id", spikeActiveId);
        updateWrapper.eq("is_deleted", 0);
        updateWrapper.set("status", staus);
        shopParticipateActiveMapper.update(new ShopParticipateActive(), updateWrapper);
    }


}
